const {getList,getDetail,newBlog,updateBlog,delBlog,delUser} = require("../control/blog")
const {SuccessModel,ErrorModel} = require("../model/resModel")

//定义一个统一的 登录验证函数
const loginCheck = (req)=>{
  if(!req.session.username){
    return new ErrorModel("尚未登录")
  }
}

const handleBlogRouter=async (req,res)=>{
  const method=req.method

  if(method=="GET"&& req.path==="/api/blog/list"){
    
    const author=req.query.author||""//如果没有 就返回""
    const keyword=req.query.keyword||""
    // const listData=getList(author,keyword)
    const listData=await getList(author,keyword)
      
      if(listData){      
        return new SuccessModel({data:listData},{msg:"获取博客列表"})
        // return listData
        
      }else{
        return new ErrorModel({msg:"没有数据"})
      }
    
    
    
  }
  //获取博客详情
  if(method==="GET"&&req.path=="/api/blog/detail"){
    const id=req.query.id||""
    if(id){
      const DetailData=await getDetail(id)
    
    if(DetailData){
      return new SuccessModel({detail:DetailData},{msg:"获取博客数据成功"})
    }else{
      return new ErrorModel({msg:"没有博客数据"})
    }
    }else{
      return new ErrorModel({msg:"请输入正缺的id"})
    }
    
  }
  
  if(method=="POST" && req.path=="/api/blog/new"){
    if(req.body){  
      const loginCheckResult = loginCheck(req)
      if(loginCheckResult){
        return 
      }
     const msg=await newBlog(req.body)
      if(msg){
        return new SuccessModel({successMsg:"添加成功"})
      }else{
        return new ErrorModel({errMessage:"添加失败"})
      }
    }else{
      return new ErrorModel({errMessage:"post请求有问题"})
    }

  }
  if(method=="POST" && req.path=="/api/blog/update"){
    if(req.body){
      const loginCheckResult = loginCheck(req)
      if(loginCheckResult){
        return 
      }
      const id=req.query.id
      const msg=await updateBlog(id,req.body)
      if(msg>0){
        return new SuccessModel({message:"更新成功"})
      }else {
        return new ErrorModel({message:"更新失败"})
      }
    }else{
      return new ErrorModel({message:"post参数有问题"})
    }
  }
  if(method=="POST" && req.path=="/api/blog/del"){
    const loginCheckResult = loginCheck(req)
      if(loginCheckResult){
        return 
      }
    const id=req.query.id||""
    console.log(id);
    
    const msg=await delBlog(id,req.body)
    
    if(msg){
      return new SuccessModel({msg:"删除成功"})
    }else{
      return new ErrorModel({msg:"删除失败"})
    }
  }
  if(method=="POST" && req.path=="/api/user/del"){
    const id=req.query.id||""
    console.log(id);
    const msg=await delUser(id,req.body)
    if(msg){
      return new SuccessModel({msg:"删除成功"})
    }else{
      return new ErrorModel({msg:"删除失败"})
    }
    
  }
  
}
module.exports=handleBlogRouter